package com.yitao.cms.service.hotSearch;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.dto.shopInfo.HotSearchDto;
import com.yitao.client.model.shopInfo.HotSearchModel;
import com.yitao.client.model.shopInfo.QHotSearchModel;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.utils.BaseUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotSearchService extends GenericEntityService<HotSearchModel, HotSearchDto, QHotSearchModel> {
    public HotSearchService(EntityManager entityManager) {
        super(entityManager);
    }
    private BaseUtils base = BaseUtils.getInstance();

    @Transactional
    public DataOutput updateHotSearch(HotSearchDto hotSearchDto, HttpServletRequest request) {
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        //参数校验
        if (hotSearchDto==null || StringUtils.isEmpty(hotSearchDto.getSearchKey())){
            return new DataOutput(CommonStatus.BAD_REQUEST);
        }

        if ( hotSearchDto.getId()!=null){//编辑
          int result =  repository.updateByWhere(Q.id.eq(hotSearchDto.getId()),it ->
                    it.set(Q.searchKey,hotSearchDto.getSearchKey()));
          if (result>0){
              return new DataOutput(CommonStatus.SUCCESS);
          }else {
              return new DataOutput(CommonStatus.SERVER_ERROR.getCode(),"修改失败，请确认参数是否有误!");
          }
        }else{//添加
            HotSearchModel hotSearchModel = new HotSearchModel();
            hotSearchModel.setCreateBy(UserSession.getUserIdBySession(request));
            hotSearchModel.setCreateTime(base.getNow());
            hotSearchModel.setIsDelete(0);//未删除
            hotSearchModel.setSearchKey(hotSearchDto.getSearchKey());
            HotSearchModel hotSearchModel1 = repository.save(hotSearchModel);
            if (hotSearchModel1!=null){
                return new DataOutput(hotSearchModel1);
            }else{
                return new DataOutput(CommonStatus.SERVER_ERROR);
            }
        }
    }

    /**
     * 熱詞查詢
     * @param searchKey
     * @param pagedInput
     * @return
     */
    public PagedOutput hotSearchList(HttpServletRequest request,String searchKey, PagedInput pagedInput){

        PagedOutput<HotSearchModel>   pagedOutput = repository.pagingList(PredicateBuilder.conjunction()
                    .ifHasTextThenAnd(searchKey,() -> Q.searchKey.like("%"+searchKey+"%"))
                .and(()->Q.isDelete.eq(0))
                .and(()->Q.createBy.eq(UserSession.getUserIdBySession(request)))
                    .get(), pagedInput, new OrderSpecifier<>(Order.DESC,Q.createTime));
            List<HotSearchDto> hotSearchDtoList = pagedOutput.getData().stream().map(this::convertEntityToDto).collect(Collectors.toList());

            return new PagedOutput(pagedInput,pagedOutput.getTotalElements(),hotSearchDtoList);

    }

    /**
     * 刪除熱手
     * @param id
     * @param request
     * @return
     */
    @Transactional
    public DataOutput deleteHotSearch(Long id, HttpServletRequest request) {
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        //参数校验
        if (id != null) {
            int result = repository.updateByWhere(Q.id.eq(id), it -> it.set(Q.isDelete, 1));
            if (result > 0) {
                return new DataOutput(CommonStatus.SUCCESS);
            } else {
                return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), "刪除失敗，請確認參數是否有誤");
            }
        }
        return new DataOutput(CommonStatus.BAD_REQUEST);
    }
}
